package com.hushan.elevator.controller;

import cn.hutool.core.bean.BeanUtil;
import com.hushan.elevator.annotation.DeviceConfig;
import com.hushan.elevator.annotation.DeviceLog;
import com.hushan.elevator.model.Department;
import com.hushan.elevator.model.User;
import com.hushan.elevator.security.SecurityUtils;
import com.hushan.elevator.service.*;
import com.hushan.elevator.utils.Result;
import com.hushan.elevator.utils.ResultCode;
import com.hushan.elevator.vo.DeptAddVo;
import com.hushan.elevator.vo.DeptUpdateVo;
import com.hushan.elevator.vo.StatisticsVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @Author: zzy
 * @Date: 2024/10/30 23:32
 * @Title:
 * @Version:
 * @Package: com.hushan.elevator.controller
 */
@Slf4j
@RequestMapping("/dept")
@RestController
@Tag(name = "DeptController", description = "单位")
public class DeptController {
    private final DeptService deptService;
    private final UserService userService;
    private final MntPersonService mntPersonService;
    private final RiskRecordService riskRecordService;
    private final DeviceInfoService deviceInfoService;


    public DeptController(DeptService deptService, UserService userService, MntPersonService mntPersonService, RiskRecordService riskRecordService, DeviceInfoService deviceInfoService) {
        this.deptService = deptService;
        this.userService = userService;
        this.mntPersonService = mntPersonService;
        this.riskRecordService = riskRecordService;
        this.deviceInfoService = deviceInfoService;
    }


    @Operation(summary = "获取所有部门", description = "返回系统中所有部门的列表")
    @GetMapping
    @DeviceLog
    public Result getAllDept() {
        User requestUser = SecurityUtils.getUser();
        Department dept = deptService.findDeptByUserId(requestUser.getUserId());
        List<Department> childByDeptId = deptService.findChildByDeptId(dept.getDeptId());
        childByDeptId.add(dept);
        return new Result(ResultCode.SUCCESS, childByDeptId);
    }

    @Operation(summary = "创建部门", description = "创建一个新的部门")
    @PostMapping
    public Result createDept(@RequestBody DeptAddVo dept) {
        if (Objects.equals(dept.getAddress(), "") || Objects.equals(dept.getName(), "")) {
            return new Result(ResultCode.FAIL);
        }
        // requester dept
        User requestUser = SecurityUtils.getUser();
        Department requestUserDept = deptService.findDeptByUserId(requestUser.getUserId());
        // create new department
        Department department = new Department();
        BeanUtil.copyProperties(dept, department);
        // new department parent is requester dept
        department.setParentId(requestUserDept.getDeptId());
        // new department ancestors are requester dept id plus this department ancestors
        department.setAncestors(requestUserDept.getAncestors()+','+requestUserDept.getDeptId());
        deptService.saveDepartment(department);
        return new Result(ResultCode.SUCCESS, department);
    }
    @Operation(summary = "根据ID获取部门", description = "根据部门ID返回部门详情")
    @GetMapping("/{id}")
    public Result getDeptById(@PathVariable Integer id) {
        // requester dept
        User requestUser = SecurityUtils.getUser();
        Department requesterDept = deptService.findDeptByUserId(requestUser.getUserId());

        // be requested dept info
        Department foundDept = deptService.findDeptById(id);
        // be requested dept ancestors
        String ancestors = foundDept.getAncestors();

        // detect authority, is the requested dept ancestors has request initiator dept
        boolean contained = deptService.detectDeptAuth(ancestors,requesterDept.getDeptId());
        if (!contained) {
            return new Result(ResultCode.UN_AUTHORISE, "没有权限");
        }
        return new Result(ResultCode.SUCCESS, foundDept);
    }

    @Operation(summary = "根据ID删除部门", description = "根据部门ID删除部门")
    @DeleteMapping("/{id}")
    public Result delDeptById(@PathVariable Integer id) {
        Department deletedDept = deptService.findDeptById(id);
        if (deletedDept == null) {
            return new Result(ResultCode.FAIL, "出错了");
        }
        if (!deptService.findUserPermissionForDept(SecurityUtils.getUser(),deletedDept)){
            return new Result(ResultCode.UN_AUTHORISE, "没有权限");
        }

        deptService.deleteDepartment(deletedDept);
        return new Result(ResultCode.SUCCESS, "删除成功");
    }


    @Operation(summary = "根据ID更新部门", description = "根据部门ID更新部门信息")
    @PutMapping("/{id}")
    public Result updateDept(@PathVariable Integer id, @RequestBody DeptUpdateVo dept) {
        Department updatedDept = deptService.findDeptById(id);
        if (updatedDept == null) {
            return new Result(ResultCode.FAIL, "出错了");
        }
        // no permission for this updated dept
        if (!deptService.findUserPermissionForDept(SecurityUtils.getUser(),updatedDept)){
            return new Result(ResultCode.UN_AUTHORISE, "没有权限1");
        }
        // no permission updated to this parent dept
        Department newParent = deptService.findDeptById(dept.getParentId());
        if (!deptService.findUserPermissionForDept(SecurityUtils.getUser(),newParent)){
            return new Result(ResultCode.UN_AUTHORISE, "没有权限2");
        }
        updatedDept.setName(dept.getName());
        updatedDept.setAddress(dept.getAddress());
        updatedDept.setParentId(dept.getParentId());
        updatedDept.setAncestors(newParent.getAncestors()+','+dept.getParentId());
        deptService.saveDepartment(updatedDept);
        return new Result(ResultCode.SUCCESS, "修改成功");
    }

    @Operation(summary = "当前部门的统计信息", description = "当前部门的统计信息,包含设备数量、维保人员数量、用户数量、风险数量、当前在线设备数量")
    @GetMapping("/stats/{id}")
    public Result getDeptStatsById(@PathVariable Integer id) {
        Department foundDepartment = deptService.findDeptById(id);
        if (foundDepartment == null) {
            return new Result(ResultCode.FAIL, "出错了");
        }
        // no permission for this updated dept
        if (!deptService.findUserPermissionForDept(SecurityUtils.getUser(),foundDepartment)){
            return new Result(ResultCode.UN_AUTHORISE, "没有权限");
        }
        StatisticsVo statistics = new StatisticsVo();
        statistics.setDeptNumb(deptService.findChildrenDeptCount(id));
//        statistics.setMntPerson(mntPersonService.findCountByDept(id));
        statistics.setDeviceNumb(deviceInfoService.findCountByDept(id));
        statistics.setOnlineDeviceNumb(deviceInfoService.findOnlineCountByDept(true,id));
        /*** 未实现 ***/
        statistics.setUserNumb(userService.findUserCountByDept(id));
        statistics.setRiskNumb(0);
        return new Result(ResultCode.SUCCESS, statistics);
    }

    @Operation(summary = "获取用户部门信息", description = "根据用户获取部门信息")
    @GetMapping("/user/{id}")
    public Result getDeptByUserId(@PathVariable Integer id) {
        // requester dept
        User requestUser = SecurityUtils.getUser();
        Department requesterDept = deptService.findDeptByUserId(requestUser.getUserId());

        // be requested dept info
        Department userDept = deptService.findDeptByUserId(id);
        return new Result(ResultCode.SUCCESS, userDept);
    }
}
